import time
import os
import requests
import uuid
from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

webdriver_path = os.path.join("util", "msedgedriver.exe")

driver = webdriver.Edge(service=Service(webdriver_path))

driver.maximize_window()

next_page_url = "https://www.defuv.com/index/index/index.html"

driver.get(next_page_url)

print("打开网页")

WebDriverWait(driver, 60).until_not(
    EC.presence_of_element_located((By.CLASS_NAME, "login-main2"))
)

button_1 = driver.find_element(
    By.XPATH, '//div[@class="el-select"]/following-sibling::img[1]'
)

button_1.click()

WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CLASS_NAME, "pic-search-box2"))
)

button_2 = driver.find_element(By.XPATH, '//div[@class="el-upload__text"]/em')

button_2.click()

input("请在网页中上传文件，然后按回车键继续。")

print("有执行到这一步")

time.sleep(10)

driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")

links = driver.find_elements(By.XPATH, '//div[@class="list-part"]//a')

link_list = [link.get_attribute("href") for link in links]

dir_path = os.path.join("resources", "yin_hua_data", "demo")
os.makedirs(dir_path, exist_ok=True)

for i, link in enumerate(link_list):
    driver.get(link)

    img_src = driver.find_element(
        By.XPATH, '//div[@class="room" and @id="content"]/img[2]'
    ).get_attribute("src")

    response = requests.get(img_src)

    file_name = f"{uuid.uuid4()}.jpg"
    file_path = os.path.join(dir_path, file_name)

    with open(file_path, "wb") as f:
        f.write(response.content)

    time.sleep(1)

driver.quit()
